// ws2812_ring.c
#include "ws2812_driver.h"
#include "stm32f4xx_hal.h"  // 根据实际芯片修改
#include <string.h>
#include "ws2812_bsp.h"

// PWM配置（与驱动层一致）
#define BITS_PER_LED    24
#define RESET_PULSE     60
#define WS2812_LOGIC_0  (PWM_PERIOD * 0.33)
#define WS2812_LOGIC_1  (PWM_PERIOD * 0.66)

// 静态缓冲区（LED数据 + 复位信号）
static uint16_t led_buffer[LED_NUM * BITS_PER_LED + RESET_PULSE];

// 初始化灯环
void WS2812_RingInit(WS2812_RingHandle *hring) 
{
    // 初始化底层驱动
    ws2812_bsp_init();
    
    // 初始化灯环状态
    memset(hring, 0, sizeof(WS2812_RingHandle));
    hring->brightness = 80;  // 默认亮度80%
    hring->dirty = 1;        // 标记需要更新
    
    // 初始化复位信号区域
    for (int i = LED_NUM * BITS_PER_LED; i < LED_NUM * BITS_PER_LED + RESET_PULSE; i++) 
	{
        led_buffer[i] = 0;
    }
}

// 设置全局亮度
void WS2812_SetBrightness(WS2812_RingHandle *hring, uint8_t brightness) 
{
    hring->brightness = (brightness > 100) ? 100 : brightness;
    hring->dirty = 1;
}

// 设置单个LED颜色
void WS2812_SetLEDColor(WS2812_RingHandle *hring, uint16_t index, RGB_Color color) 
{
    if (index >= LED_NUM) return;
    
    hring->leds[index] = color;
    hring->dirty = 1;
}

// 设置整个灯带颜色
void WS2812_SetAllColor(WS2812_RingHandle *hring, RGB_Color color) 
{
    for (int i = 0; i < LED_NUM; i++) 
	{
        hring->leds[i] = color;
    }
    hring->dirty = 1;
}

// 清除灯带
void WS2812_ClearAll(WS2812_RingHandle *hring) 
{
    RGB_Color black = {0, 0, 0};
    WS2812_SetAllColor(hring, black);
}

// 应用亮度调整
static RGB_Color apply_brightness(RGB_Color color, uint8_t brightness) 
{
    return (RGB_Color) 
	{
        .r = (color.r * brightness) / 100,
        .g = (color.g * brightness) / 100,
        .b = (color.b * brightness) / 100
    };
}

// 将颜色值转换为PWM位数据
static void color_to_bits(RGB_Color color, uint16_t *buffer_pos) 
{
    // 注意：WS2812使用GRB顺序
    uint8_t colors[3] = {color.g, color.r, color.b};
    
    for (int c = 0; c < 3; c++) 
	{          // 遍历GRB三个通道
        for (int b = 7; b >= 0; b--) 
		{     // 从高位到低位
            *buffer_pos++ = (colors[c] & (1 << b)) 
                            ? WS2812_LOGIC_1 
                            : WS2812_LOGIC_0;
        }
    }
}

// 更新灯带
void WS2812_UpdateRing(WS2812_RingHandle *hring) 
{
    if (!hring->dirty) return;
    
    // 转换所有LED数据
    uint16_t *buf_ptr = led_buffer;
    for (int i = 0; i < LED_NUM; i++) {
        RGB_Color adj_color = apply_brightness(hring->leds[i], hring->brightness);
        color_to_bits(adj_color, buf_ptr);
        buf_ptr += BITS_PER_LED;
    }
    
    // 启动传输
    WS2812_Start_Transfer(led_buffer, LED_NUM * BITS_PER_LED + RESET_PULSE);
    hring->dirty = 0;
}
